import { getUserInfo } from '@/api/user'
import { login, register } from '@/api/login'
import { setToken, getToken, delToken, setUserInfo, delUserInfo } from '@/utils/auth'

export default {
    state: {
        token: getToken(),
        uuid: null,
        nickname: null,
        avatar: null,
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
        },
        setUuid(state, uuid) {
            state.uuid = uuid;
        },
        setNickname(state, nickname) {
            state.nickname = nickname;
        },
        setAvatar(state, avatar) {
            state.avatar = avatar;
        },
    },
    getters: {
        token: state => state.token,
        avatar: state => state.avatar,
        uuid: state => state.uuid,
        nickname: state => state.nickname,
    },
    actions: {
        // 登录
        handleLogin({ commit }, { username, password, authCode }) {
            return new Promise((resolve, reject) => {
                login(username, password, authCode).then(res => {
                    const data = res.data;
                    const tokenStr = data.tokenHead + data.token;
                    setToken(tokenStr);
                    commit('setToken', tokenStr);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        },
        // 注册
        handleRegister({ commit }, { username, password, nickname, authCode }) {
            return new Promise((resolve, reject) => {
                register(username, password, nickname, authCode).then(res => {
                    const data = res.data;
                    const tokenStr = data.tokenHead + data.token;
                    setToken(tokenStr);
                    commit('setToken', tokenStr);
                    resolve();
                }).catch(err => {
                    reject(err);
                })
            })
        },
        // 获取用户信息
        getUserInfo({ state, commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const data = res.data;
                    commit('setUuid', data.uuid);
                    commit('setNickname', data.nickname);
                    commit('setAvatar', data.avatar);
                    resolve(data);
                }).catch(err => {
                    reject(err);
                })
            })
        },
        // 前端 登出
        fedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('setToken', '')
                delToken()
                localStorage.clear();
                resolve()
            })
        }
    }
}